<style lang="less" scoped>
.scroll {
  &-view {
    text-align: left;
    white-space: nowrap;
    overflow-x: scroll;
    position: relative;
    font-size: 0;
    letter-spacing: 0;
  }
  &-item {
    display: inline-block;
    padding: 8px 18px;
    font-size: 16px;
    letter-spacing: 0;
  }
  &-slider {
    position: absolute;
    content: ' ';
    bottom: 20px;
    height: 1px;
    background-color: #3399ff;
    transition: all 0.3s;
    // left: 0;
  }
  &-hide {
    font-size: 0;
    letter-spacing: 0;
    height: 0;
    overflow: hidden;
    &__item {
      display: inline;
      font-size: 16px;
    }
    #scrollW {
      padding: 0;
    }
    #scrollWP {
      padding: 0 0 0 18px;
    }
  }
}
.active {
  color: #3399ff;
}
</style>

<template>
  <!-- tab-bar -->
  <scroll-view class='scroll-view' scroll-x="true" @click="tabClick">
    <div :class="['scroll-item',{active:activeIndex==index}]" v-for="(item,index) in tabs" :key="index" :id="'scroll'+index" :data-index="index">{{item}}</div>
    <div class="scroll-slider" :style="sliderStyle"></div>
  </scroll-view>
</template>
<script>
export default {
  props: ['activeIndex', 'tabs'],
  data() {
    return {
      sliderStyle: ''
    };
  },
  mounted() {
    setTimeout(() => {
      this.getRects();
    }, 100);
  },
  computed: {},
  methods: {
    tabClick(e) {
      const index = e.target.dataset.index || 0;
      // tab点击回调
      this.$emit('indexChange', index);
      this.getCurrentTab();
    },
    getRects() {
      // 获取tab元素列表

      wx
        .createSelectorQuery()
        .selectAll('.scroll-item')
        .boundingClientRect(rects => {
          console.log(rects);
          this.rects = rects;
          this.getCurrentTab();
        })
        .exec();
    },
    getCurrentTab() {
      // 获取当前tab元素的位置
      if (!this.rects) return;

      const currentTab = this.rects[this.activeIndex];

      if (!currentTab) return;
      const bottom = currentTab.bottom;
      const left = currentTab.left;
      const right = currentTab.right;
      const width = right - left;
      const s = `left:${left}rpx;width:${width}rpx;`;

      this.sliderStyle = s;
    }
  }
};
</script>
